<?php

namespace App\Http\Controllers\Admin;

use App\Model\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

//客户板块控制器
class CustomerController extends Controller
{
    //客户列表
    public function list(){
        if(request()->ajax()){
            //分页信息
            $page = request('page');
            $limit = request('limit');
            //查询数据
            $search = json_decode(request('searchParams'),true);
            $cus_name = $search['cus_name'];
            $mobile = $search['mobile'];
            $company = $search['company'];

            $offset = $limit*($page - 1);
            $res = Customer::where(function ($query) use($cus_name){
                    if($cus_name){
                        $query->where('cus_name','like',"%$cus_name%");
                    }
                })
                ->where(function ($query) use($mobile){
                    if($mobile){
                        $query->where('mobile','like',"%$mobile%");
                    }
                })
                ->where(function ($query) use($company){
                    if($company){
                        $query->where('company','like',"%$company%");
                    }
                })
                ->orderBy('add_time','desc')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $count = Customer::count();

            return json_encode(['code'=>0,'count'=>$count,'data'=>$res,'msg'=>'']);
        }

        return view('customer.list');
    }
    //添加客户
    public function add(){
        if(request()->isMethod('post')){
            request()->flash();
            $this->validate(request(),[
                'cus_name' => 'bail|required|between:2,6' ,
                'mobile' => 'bail|required|regex:/^1[356789]\d{9}$/'
            ],[
                'cus_name.required' => '客户名称不能为空',
                'cus_name.between' => '客户名称再2~6位之间',
                'mobile.required' => '手机号不能为空',
                'mobile.regex' => '请填写正确的手机号'
            ]);

            $data = request()->except('_token');
            $data['add_time'] = time();
            if(Customer::insert($data)){
                return json_encode(['status' => 'ok' ,'msg' => '添加成功']);
            }else{
                return json_encode(['status' => 'error' ,'msg' => '添加失败']);
            }

        }
        return view('customer.add');
    }
    //删除客户
    public function dels(){

        $ids = request('data');

        if(Customer::destroy($ids)){
            return json_encode(['status'=>'ok','msg'=>'删除成功']);
        }else{
            return json_encode(['status'=>'error','msg'=>'删除失败']);
        }
    }
    //修改客户
    public function edit($id){
        dd($id);
    }
}
